class dryPhone extends HTMLElement{
    constructor(){
        super();
        var that = this;
        var ref = get("ref");
        var callback = get("callback");
        var label = get("label");
        var url = get("url");
        var cardColor = get("cardColor", "#009688");
        var phoneName = get("phoneName", "dry_phone");
        var phonePlaceholder = get("phonePlaceholder", "请输入手机号");
        var imageCodeName = get("imageCodeName", "dry_image_code");
        var imageCodePlaceholder = get("imageCodePlaceholder", "请输入图片验证码");
        var phoneCodeName = get("phoneCodeName", "dry_code");
        var phoneCodePlaceholder = get("phoneCodePlaceholder", "请输入短信验证码");
        var imageName = get("imageName");
        var imageUrl = get("imageUrl");
        var checkUrl = get("checkUrl");
        var imageCodeLength = get("imageCodeLength", 6);
        var buttonClass = get("buttonClass", "");
        var regetButtonClass = get("regetButtonClass", "layui-btn-disabled");
        var time = get("time", 60);
        
        function get(name, theDefault = "")
        {
            if(that.hasAttribute(name)){
                return that.getAttribute(name);
            }
            return theDefault;
        }
        
        function $$(id)
        {
            return document.getElementById(id);
        }
        
        function isPhone(test)
        {
            return /^1[3-9]{1}\d{9}$/.test(test);
        }
        
        function getUnique()
        {
            var d = new Date();
            var temp = Math.random() + "";
            return "g_" + d.getTime() + "_" + temp.substr(2);
        }
        
        function httpBuildQuery(data)
        {
            var list = [];
            for(var key in data){
                var value = data[key];
                list.push(key + "=" + value);
            }
            return list.join("&");
        }
        
        function getRequest(url, successCallback, failCallback)
        {
            function success(response)
            {
                if(response.ok == true && response.status == 200){
                    response.json().then(function(json){
                        successCallback(json);
                    });
                }
            }
            
            function fail(response)
            {
                if(typeof(failCallback) == "function"){
                    failCallback(response);
                }
                else{
                    console.log(response);
                }
            }
            
            fetch(url, {method: "GET", credentials: "include"}).then(success).catch(fail);
        }
        
        function runCallback(p)
        {
            var f = window[callback];
            if(!f){
                setTimeout(function(){
                    runCallback(p);
                }, 500);
            }
            else{
                f(p);
                that.setAttribute("ok", "1");
            }
        }
        
        function finish()
        {
            var html = [];
            html.push(`<div class="layui-form-item">`);
            /*layui-card start*/
            html.push(`<div class="layui-card">`);
            html.push(`<div class="layui-card-header layui-unselect" style="background-color:${cardColor};border:1px solid ${cardColor};color:white;">${label}</div>`);
            html.push(`<div class="layui-card-body" style="border:1px solid ${cardColor};margin-top:-1px;">`);
            /*layui-card-body start*/
            var image = `
            <div style="position:relative;width:100%;">
                <input type="text" class="layui-input" name="${imageCodeName}" id="${imageCodeName}" lay-verify="${imageCodeName}" placeholder="${imageCodePlaceholder}">
                <img src="" name="${imageName}" id="${imageName}" width="100" height="38" data-src="${imageUrl}" style="position:absolute;right:0;top:0;width:100px;height:38px;cursor:pointer;display:none;"/> 
            </div>
            `;
            html.push(image);
            html.push(`<input type="text" class="layui-input" name="${phoneName}" id="${phoneName}" lay-verify="${phoneName}" placeholder="${phonePlaceholder}" style="margin-top:10px;">`);
            html.push(`<input type="text" class="layui-input" name="${phoneCodeName}" id="${phoneCodeName}" lay-verify="${phoneCodeName}" placeholder="${phoneCodePlaceholder}" style="margin-top:10px;">`);
            html.push(`<button type="button" class="layui-btn layui-btn-fluid ${buttonClass} dry-get-button" style="margin-top:10px;">获取短信验证码</button>`);
            html.push(`<button type="button" class="layui-btn layui-btn-fluid ${regetButtonClass} dry-reget-button" style="margin-top:10px;margin-left:0;display:none;"><span>${time}</span>秒后重试</button>`);
            /*layui-card-body end*/
            html.push(`</div>`);
            html.push(`</div>`);
            /*layui-card end*/
            html.push(`</div>`);
            if(ref == ""){
                ref = getUnique();
                that.insertAdjacentHTML("afterend", `<div id="${ref}"></div>`);
            }
            $$(ref).innerHTML = html.join("");
            runCallback(commonCallback);
        }
        
        function commonCallback(y, f)
        {
            function render()
            {
                form.render();
            }
            
            function success(json)
            {
                if(json.code > 0){
                    layer.msg(json.msg);
                }
                else{
                    layer.msg("短信验证码已发送");
                }
            }
            
            function init()
            {
                var getButton = $("#" + phoneName).parent().find(".dry-get-button");
                var regetButton = $("#" + phoneName).parent().find(".dry-reget-button");
                var countDown = regetButton.find("span");
                var lock = 0;
                getButton.click(function(){
                    /*如果正在请求验证图片验证码是否正确的过程中 start*/
                    if(isAjax){
                        setTimeout(function(){
                            getButton.trigger("click");
                        }, 1000);
                        return false;
                    }
                    /*如果正在请求验证图片验证码是否正确的过程中 end*/
                    /*锁 start*/
                    if(lock){
                        return false;
                    }
                    lock = 1;
                    window.setTimeout(function(){
                        lock = 0;
                    }, 1000);
                    /*锁 end*/
                    if(!checkResult){
                        layer.msg('图片验证码不正确');
                        return false;
                    }
                    var phone = $("#" + phoneName).val();
                    if(!isPhone(phone)){
                        layer.msg('手机号不正确');
                        return false;
                    }
                    var parameter = {
                        imageName: imageName,
                        imageCode: $("#" + imageCodeName).val(),
                        phone: phone
                    };
                    var requestUrl = url + "?" + httpBuildQuery(parameter);
                    getRequest(requestUrl, success);
                    getButton.hide();
                    regetButton.show();
                    /*倒计时 start*/
                    var theId = window.setInterval(function(){
                        var i = countDown.html();
                        i--;
                        if(i <= 0){
                            countDown.html(time);
                            window.clearInterval(theId);
                            getButton.show();
                            regetButton.hide();
                        }
                        else{
                            countDown.html(i);
                        }
                    }, 1000);
                    /*倒计时 end*/
                });
            }
            
            function initImage()
            {
                function refresh()
                {
                    var img = $("#" + imageName);
                    var src = img.attr("data-src") + "?n=" + img.attr("name") + "&w=" + img.attr("width") + "&h=" + img.attr("height") + "&r=" + Math.random();
                    img.attr("src", src).show();
                }
            
                $("#" + imageName).click(function(){
                    refresh();
                    checkResult = false;
                });
                
                refresh();
            }
            
            function blur()
            {
                var element = $("#" + imageCodeName);
                element.on("blur", function(){
                    function checkRequestSuccess(json)
                    {
                        if(json.code > 0){
                            checkResult = false;
                        }
                        else{
                            checkResult = true;
                        }
                        isAjax = false;
                    }
                    /*验证码长度都不满足要求则直接跳过 start*/
                    if(element.val().length != imageCodeLength){
                        checkResult = false;
                        return false;
                    }
                    /*验证码长度都不满足要求则直接跳过 end*/
                    isAjax = true;
                    checkResult = false;
                    var parameter = {
                        imageName: imageName,
                        imageCode: $("#" + imageCodeName).val()
                    };
                    var requestUrl = checkUrl + "?" + httpBuildQuery(parameter);
                    getRequest(requestUrl, checkRequestSuccess);
                });
            }
            
            var form = y.form;
            var $ = y.jquery;
            var layer = y.layer;
            var isAjax = false;
            var checkResult = false;
            init();
            initImage();
            blur();
            render();
        }
        
        if(callback == ""){
            callback = "dryCallback";
        }
        finish();
    }
};
window.customElements.define('dry-phone', dryPhone);